<?php

namespace app\api\controller;

use app\admin\model\express\Packagetrack;
use app\admin\model\express\Warehouse;
use app\admin\model\OrderExpress;
use app\admin\model\PackageGoods;
use app\common\controller\Api;
use app\common\library\Express100;
use think\Config;
use think\Db;
use think\Exception;

/**
 * 订单接口
 */
class Package extends Api
{
    protected $noNeedLogin = ['warehouse','a','track'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    // 仓库地址
    public function warehouse()
    {
        $list = Db::name("express_warehouse")->field(['id','title'])->select();
        $this->success('ok', $list);
    }

    //列表
    public function list()
    {
        $userId = $this->auth->id;
        $status = (int)$this->request->param('status', 0); //1待入库，2已入库，3已发货
        $where = [];
        $where['user_id'] = $userId;
        if ($status > 0) {
            $where['status'] = $status;
        }
        $package = new \app\admin\model\express\Package();
        $list = $package->order("id desc")->where($where)->paginate();
        $this->success("", $list);
    }

    //详情
    public function detail(){
        $id = $this->request->param('id');
        $user_id = $this->auth->id;
        $info = Db::name("express_package")->where(['user_id'=>$user_id,'id'=>$id])->find();
        if(empty($info)){
            $this->error("包裹不存在");
        }
        $goods_list = Db::name("express_package_goods")->where(['package_id'=>$info['id']])->select();
        $this->success("ok",['package'=>$info,'goods_list'=>$goods_list]);
    }

    //入库扫码
    public function scan(){
        $from_express_no = $this->request->param('from_express_no','','trim');
        $info = Db::name("express_package")->where(['from_express_no'=>$from_express_no])->find();
        if(empty($info)){
            $this->success("ok",['type'=>1]);
        }else{
             if($info['state']>1){
                 $this->error("包裹已入库");
             }
            $goods_list = Db::name("express_package_goods")->where(['package_id'=>$info['id']])->select();
            $this->success("ok",['package'=>$info,'goods_list'=>$goods_list,'type'=>2]);
        }
    }


    public function a(){
        $eg_data = [
            'order_list'=>[
                [
                    'from_express_no'=>'a',
                    'weight'=>'10',
                    'line_id'=>'1',
                    'insure_price'=>'100',
                    'tax_price'=>200,
                    'remark'=>'备注',
                    'goods_list'=>[
                        ['name'=>'华为手机','number'=>'1','brand'=>'华为','sku'=>'asfsdf']
                    ],
                ],
            ],
            'from_address'=>[
                'from_username'=>'zdw',
                'from_mobile'=>'132456789',
                'from_email'=>'123@qq.com',
                'from_address'=>'adfsd',
                'from_post_code'=>'1122',
            ],
            'to_address'=>[
                'to_username'=>'aa',
                'to_mobile'=>'122333333',
                'to_province'=>'河南',
                'to_city'=>'郑州',
                'to_district'=>'金水区',
                'to_address'=>'花园路10号',
                'to_post_code'=>'33366',
                'to_id_code'=>'11111111',
                'to_id_z_image'=>'/upload/a.png',
                'to_id_f_image'=>'/upload/b.png',
            ],
        ];

        echo json_encode($eg_data,JSON_UNESCAPED_UNICODE);die;
    }

    //预报订单
    public function addOrder(){
        $eg_data = [
            'order_list'=>[
                [
                    'from_express_no'=>'a',
                    'weight'=>'10',
                    'line_id'=>'1',
                    'insure_price'=>'100',
                    'tax_price'=>200,
                    'post_price'=>200,
                    'goods_list'=>[
                        ['name'=>'华为手机','number'=>'1','brand'=>'华为']
                    ],
                ],
            ],
            'from_address'=>[
                'from_username'=>'zdw',
                'from_mobile'=>'132456789',
                'from_email'=>'123@qq.com',
                'from_address'=>'adfsd',
                'from_post_code'=>'1122',
            ],
            'to_address'=>[
                'to_username'=>'aa',
                'to_mobile'=>'122333333',
                'to_province'=>'河南',
                'to_city'=>'郑州',
                'to_district'=>'金水区',
                'to_address'=>'花园路10号',
                'to_post_code'=>'33366',
                'to_id_code'=>'11111111',
                'to_id_z_image'=>'/upload/a.png',
                'to_id_f_image'=>'/upload/b.png',
            ],
        ];

        $data = $this->request->post();
        $this->request->filter(['trim']);
        $user_id = $this->auth->id;
        $data['user_id'] = $user_id;
        $from_address = $this->request->post('from_address/a');
        $to_address = $this->request->post('to_address/a');
        $order_list = $this->request->post('order_list/a');
        if(empty($from_address) || !is_array($from_address)){
            $this->error("发件人地址信息不能为空");
        }
        $from_address_validate = new \think\Validate([
            'from_username|发件人名称' => 'require|max:30',
            'from_mobile|发件人手机号' => 'require|max:15',
            'from_email|发货人邮箱' => 'email|max:100',
            'from_address|发货人地址' => 'require|max:100',
            'from_post_code|发货人邮编' => 'require|max:10',
        ]);
        if (!$from_address_validate->check($from_address)) {
            $this->error($from_address_validate->getError());
        }

        if(empty($to_address) || !is_array($to_address)){
            $this->error("收件人地址信息不能为空");
        }
        $to_address_validate = new \think\Validate([
            'to_username|收件人名称' => 'require|max:30',
            'to_mobile|收件人手机号' => 'require|max:15',
            'to_province|收货人省' => 'max:30',
            'to_city|收货人城市' => 'max:40',
            'to_district|收货人地区' => 'max:60',
            'to_address|收货人地址' => 'require|max:100',
            'to_post_code|收货人邮编' => 'max:10',
            'to_id_code|收货人身份证号' => 'max:30',
            'to_id_z_image|收货人身份证正面' => 'max:150',
            'to_id_f_image|收货人身份证反面' => 'max:150',
        ]);
        if (!$to_address_validate->check($to_address)) {
            $this->error($to_address_validate->getError());
        }

        if(empty($order_list) || !is_array($order_list)){
            $this->error("订单信息不能为空");
        }
        $order_validate = new \think\Validate([
            'from_express_no|快递单号' => 'require',
            'line_id|分类' => 'require',
            'weight|重量' => 'require|float',
            'insure_price|保险费' => 'float',
            'tax_price|税费' => 'float',
        ]);


        Db::startTrans();
        try{
            foreach ($order_list as $order){
                if (!$order_validate->check($order)) {
                    throw new Exception($order_validate->getError());
                }
                $from_express_no = $order['from_express_no']??"";
                if(empty($from_express_no)){
                    throw new Exception("来源单号不能为空");
                }
                $num = Db::name("express_package")->where(['from_express_no'=>$from_express_no])->count();
                if($num > 0){
                    throw new Exception("来源单号已存在");
                }

                $goods_list = $order['goods_list']??"";
                if(empty($goods_list) || !is_array($goods_list)){
                    throw new Exception("请添加物品");
                }
                $goods_validate = new \think\Validate([
                    'name|物品名称' => 'require',
                    'number|数量' => 'require|number',
                ]);
                foreach ($goods_list as $goods){
                    if (!$goods_validate->check($goods)) {
                        throw new Exception($goods_validate->getError());
                    }
                }

                $order = array_merge($order,$from_address);
                $order = array_merge($order,$to_address);

                $model = new \app\admin\model\express\Package();
                $package_goods_model = new PackageGoods();
                $order['package_no'] = uniqid(true);
                $order['user_id'] = $user_id;
                $res = $model->allowField(true)->save($order);
                if(empty($res)){
                    throw new Exception("提交失败");
                }
                foreach ($goods_list as &$goods_list_val){
                    $goods_list_val['package_id'] = $model->id;
                }
                $res = $package_goods_model->allowField(true)->saveAll($goods_list);
                if(empty($res)){
                    throw new Exception("提交失败");
                }
            }

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("ok");
    }

    //编辑订单
    public function editOrder(){
        $eg_data = [
            'id'=>1,
            'order'=>[
                    'from_express_no'=>'a',
                    'weight'=>'10',
                    'line_id'=>'1',
                    'insure_price'=>'100',
                    'tax_price'=>200,
                    'post_price'=>200,
                    'goods_list'=>[
                        ['name'=>'华为手机','number'=>'1','brand'=>'华为']
                    ],
            ],
            'from_address'=>[
                'from_username'=>'zdw',
                'from_mobile'=>'132456789',
                'from_email'=>'123@qq.com',
                'from_address'=>'adfsd',
                'from_post_code'=>'1122',
            ],
            'to_address'=>[
                'to_username'=>'aa',
                'to_mobile'=>'122333333',
                'to_province'=>'河南',
                'to_city'=>'郑州',
                'to_district'=>'金水区',
                'to_address'=>'花园路10号',
                'to_post_code'=>'33366',
                'to_id_code'=>'11111111',
                'to_id_z_image'=>'/upload/a.png',
                'to_id_f_image'=>'/upload/b.png',
            ],
        ];
        $id = $this->request->param('id');
        if($id<1){
            $this->error("缺少参数");
        }
        $user_id = $this->auth->id;
        $model = model('\app\admin\model\express\Package')->where(['user_id'=>$user_id,'id'=>$id])->find();
        if(empty($model)){
            $this->error("包裹数据不存在");
        }
        if($model['status'] != 1){
            $this->error("包裹已入库，无法修改");
        }

       // $data = $this->request->post();
        $this->request->filter(['trim']);
        $user_id = $this->auth->id;
       // $data['user_id'] = $user_id;
        $from_address = $this->request->post('from_address/a');
        $to_address = $this->request->post('to_address/a');
        $order = $this->request->post('order/a');
        if(empty($from_address) || !is_array($from_address)){
            $this->error("发件人地址信息不能为空");
        }
        $from_address_validate = new \think\Validate([
            'from_username|发件人名称' => 'require|max:30',
            'from_mobile|发件人手机号' => 'require|max:15',
            'from_email|发货人邮箱' => 'email|max:100',
            'from_address|发货人地址' => 'require|max:100',
            'from_post_code|发货人邮编' => 'require|max:10',
        ]);
        if (!$from_address_validate->check($from_address)) {
            $this->error($from_address_validate->getError());
        }

        if(empty($to_address) || !is_array($to_address)){
            $this->error("收件人地址信息不能为空");
        }
        $to_address_validate = new \think\Validate([
            'to_username|收件人名称' => 'require|max:30',
            'to_mobile|收件人手机号' => 'require|max:15',
            'to_province|收货人省' => 'max:30',
            'to_city|收货人城市' => 'max:40',
            'to_district|收货人地区' => 'max:60',
            'to_address|收货人地址' => 'require|max:100',
            'to_post_code|收货人邮编' => 'max:10',
            'to_id_code|收货人身份证号' => 'max:30',
            'to_id_z_image|收货人身份证正面' => 'max:150',
            'to_id_f_image|收货人身份证反面' => 'max:150',
        ]);
        if (!$to_address_validate->check($to_address)) {
            $this->error($to_address_validate->getError());
        }
        $order = $order[0]??"";
        if(empty($order) || !is_array($order)){
            $this->error("订单信息不能为空");
        }
        $order_validate = new \think\Validate([
            'from_express_no|快递单号' => 'require',
            'line_id|分类' => 'require',
            'weight|重量' => 'require|float',
            'insure_price|保险费' => 'float',
            'tax_price|税费' => 'float',
        ]);


        Db::startTrans();
        try{
                if (!$order_validate->check($order)) {
                    throw new Exception($order_validate->getError());
                }
                $from_express_no = $order['from_express_no']??"";
                if(empty($from_express_no)){
                    throw new Exception("来源单号不能为空");
                }
                $num = Db::name("express_package")->where("id","<>",$id)->where(['from_express_no'=>$from_express_no])->count();
                if($num > 0){
                    throw new Exception("来源单号已存在");
                }

                $goods_list = $order['goods_list']??"";
                if(empty($goods_list) || !is_array($goods_list)){
                    throw new Exception("请添加物品");
                }
                $goods_validate = new \think\Validate([
                    'name|物品名称' => 'require',
                    'number|数量' => 'require|number',
                ]);
                foreach ($goods_list as $goods){
                    if (!$goods_validate->check($goods)) {
                        throw new Exception($goods_validate->getError());
                    }
                }

                $order = array_merge($order,$from_address);
                $order = array_merge($order,$to_address);

                $package_goods_model = new PackageGoods();
                $order['user_id'] = $user_id;
                $res = $model->allowField(true)->save($order);
                if(empty($res)){
                    throw new Exception("提交失败");
                }
                $goods_ar = [];
                foreach ($goods_list as $goods_list_val){
                    $goods_ar[] =[
                        'name'=>$goods_list_val['name'],
                        'brand'=>$goods_list_val['brand'],
                        'sku'=>$goods_list_val['sku'],
                        'number'=>$goods_list_val['number'],
                        'package_id'=>$id
                    ];
                }
                Db::name("express_package_goods")->where(['package_id'=>$id])->delete();
                $res = $package_goods_model->allowField(true)->saveAll($goods_ar);
                if(empty($res)){
                    throw new Exception("提交失败");
                }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("ok");
    }

    //删除订单
    public function delOrder(){
        $id = $this->request->param('id');
        if($id<1){
            $this->error("缺少参数");
        }
        $user_id = $this->auth->id;
        $model = model('\app\admin\model\express\Package')->where(['user_id'=>$user_id,'id'=>$id])->find();
        if(empty($model)){
            $this->error("包裹数据不存在");
        }
        if($model['status'] != 1){
            $this->error("包裹已入库，无法删除");
        }
        Db::name("express_package")->where(['id'=>$id])->delete();
        Db::name("express_package_goods")->where(['package_id'=>$id])->delete();

        $this->success("删除成功");
    }

    //入库
    public function store(){
        $from_express_no = $this->request->param('from_express_no', '', 'trim');
        if(empty($from_express_no)){
            $this->error("缺少参数");
        }
        $info = Db::name("express_package")->where("from_express_no",$from_express_no)->find();
        if(empty($info)){
            $user_id = (int)$this->request->param('user_id');
            if($user_id < 1){
             //   $this->error("缺少用户id");
            }
            $check_user = Db::name("user")->where(['id'=>$user_id])->count();
            if($user_id>0 && empty($check_user)){
                $this->error("用户id不存在");
            }
            $order = [];
            $model = new \app\admin\model\express\Package();
            $order['package_no'] = uniqid(true);
            $order['user_id'] = $user_id;
            $order['from_express_no'] = $from_express_no;
            $order['status'] = 2;
            $order['is_complete'] = 0;
            $res = $model->allowField(true)->save($order);
            $this->success("入库成功");
        }else{
            if($info['status']>1){
                $this->error("包裹已入库");
            }
            Db::name("express_package")->where(['from_express_no'=>$from_express_no])->update(['status'=>2]);
            $this->success("入库成功");
        }

    }

    //包裹入库
    public function storeok()
    {
        $userId = $this->request->param('user_id', 0, 'intval');
        $address_id = $this->request->param('address_id', 0, 'intval');  //仓库id
        $expressNo = $this->request->param('express_no', '', 'trim');
        $price = $this->request->param('price', 0);
        $price = sprintf("%.2f",$price);

        $expressName = $this->request->param('express_name', '', 'trim');
        $images = $this->request->param('images', '', 'trim');
        $remarks = $this->request->param('remarks', '', 'trim');
        if(empty($expressNo)){
            $this->error("缺少单号参数");
        }
        if($price<=0){
            $this->error("请填写价格");
        }


        if($userId>0){
            $userIsIsist = (new \app\common\model\User())->where(['id' => $userId])->count();
            if (!$userIsIsist) {
                $this->error("用户不存在");
            }
        }
        if(!is_array($expressNo)){
            $expressNo = explode(',',$expressNo);
        }


        $packageExist = (new \app\admin\model\express\Package())->whereIn('express_no', $expressNo)->count();
        if ($packageExist) {
            $this->error("快递单号已经存在");
        }

        Db::startTrans();
        try {
            foreach ($expressNo as $expressNo_val){
                $date = [
                    'user_id' => $userId,
                    'batch_id' => 0,
                    'package_no' => orderOn($userId),
                    'express_no' => $expressNo_val,
                    'express_name' => $expressName,
                    'images' => $images,
                    'remarks' => $remarks,
                    'status' => 2,
                    'track_id' => 0,
                    'work_id' => $this->auth->id,
                    'to_warehouse_id'=>$address_id,
                    'price'=>$price,
                    'to_warehouse_time'=>time()
                ];
                $package = new \app\admin\model\express\Package();
                $res = $package->allowField(true)->save($date);
                $id = $package->id;
                $model = new Packagetrack();
                $log = [
                    'package_id'=>$id,
                    'track_id'=>0,
                    'msg'=>"包裹已入仓",
                    'admin_id'=>0,
                    'createtime'=>time()
                ];
                $res = $model->allowField(true)->save($log);
                if (empty($res)) {
                    throw new Exception("操作失败");
                }
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('入库成功');
    }

    //到达扫码
    public function arriveScan(){
        $express_no = $this->request->param('express_no');
        if(empty($express_no)){
            $this->error("缺少参数");
        }
        //new  \app\admin\model\express\Package();
        $info = Db::name("express_package")->where(['express_no'=>$express_no])->field(['id','batch_id','status','express_no','arrive_time'])->find();
        if(empty($info)){
            $this->error("数据不存在");
        }
        if($info['batch_id']<1){
            $this->error("还没用加入批次");
        }
        if($info['arrive_time']>100){
            $this->error("已扫到达码入库");
        }

        $this->success('ok',$info);
    }

    //到达入库
    public function setArrive(){
        $ids = $this->request->param('ids');
        $get = $this->request->get();
        $post = $this->request->post();
        if(empty($ids)){
            $this->error("缺少参数",['get'=>$get,'post'=>$post]);
        }
        $list = Db::name("express_package")->whereIn("id",$ids)
            ->where("batch_id",">",0)
            ->where('arrive_time','<',100)
            ->field(['id','batch_id','status','express_no','arrive_time'])->select();
        if(empty($list)){
            $this->error("数据不存在");
        }
        $worker_id = $this->auth->id;
        $nowTime = time();
        $log_list = [];
        $ids = [];
        foreach ($list as $val){
            $ids[] = $val['id'];
            $log = [
                'package_id'=>$val['id'],
                'track_id'=>0,
                'msg'=>"包裹已到达目的地，快递小哥正在派送中",
                'admin_id'=>0,
                'createtime'=>$nowTime
            ];
            $log_list[] = $log;
        }

        $model = new Packagetrack();
        Db::startTrans();
        try {
            $model->allowField(true)->saveAll($log_list);
            Db::name("express_package")->whereIn("id",$ids)->update(
              ['arrive_time'=>$nowTime,'arrive_work_id'=>$worker_id]
            );
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("操作成功");
    }

    //包裹轨迹
    public function track_bak()
    {
        $packageId = $this->request->param('package_id', 0, 'intval');
        $packageTrack = new Packagetrack();
        $list = $packageTrack->with(['track'])->where(['package_id' => $packageId])->order("id desc")->select();
        $this->success("", $list);
    }
    //包裹轨迹
    public function track()
    {
        $packageId = $this->request->param('express_no', 0, 'trim');
        if(empty($packageId)){
            $this->error("请输入单号");
        }
        $packageTrack = new Packagetrack();
        if(is_numeric($packageId)){
            $info = Db::name("express_package")->where(['id'=>$packageId])->field(['id','express_no','to_mobile'])->find();
        }
        if(empty($info)){
            $info = Db::name("express_package")->where(['from_express_no'=>$packageId])->field(['id','express_no','to_mobile'])->find();
            if(empty($info)){
                $this->error("包裹未入库，暂无此包裹信息");
            }
        }
        $list = $packageTrack->where(['package_id' => $info['id']])->order("id desc")->select();
        if(empty($list)){
            $this->error("暂无此包裹信息");
        }
        $track_ar = Db::name("express_track")->column("contents",'id');
        foreach ($list as &$val){
            $val['createtime_text']= $val['time']?$val['time']:date("Y-m-d H:i:s",$val['createtime']);
            $val['content'] = $track_ar[$val['track_id']]??"";
        }

        $list1 = "";
        if($info['express_no']){
            $list1 = $this->getExpress($info['express_no'],$info['to_mobile']);
            $ar = [];
            if($list1 && isset($list1['data']) && $list1['data']){
                $arr = [];
                foreach ($list1['data'] as $data_val){
                    array_unshift($arr,['content'=>$data_val['context'],'time'=>$data_val['time']]);
                }
                foreach ($arr as $arr_val){
                    array_unshift($list,$arr_val);
                }
            }
        }
        $data = [
            'list'=>$list,
           // 'list1'=>$list1
        ];

        $this->success("", $data);
    }


    /** 获取订单物流信息
     * @param $orderSn
     * @param $express_number
     * @return bool|mixed
     */
    private  function getExpressData($express_number){
        $data= Db::name("order_express")->where(['express_number'=>$express_number])->find();
        if(empty($data) || empty($data['data'])) return false;
        //超过五个小时，不再使用数据库数据
        $nowTime = time();
        if(($nowTime - $data['updatetime'])>3600*6) return false;
        return $data;
    }
    //获取物流信息
    public function getExpress($express_no,$mobile=''){
        $expressData = null;
        try{
            //$expressData = $this->getExpressData($express_no);
            $expressData = null;;
            if(empty($expressData)){
                $expressData = $this->setExpressData($express_no,'',$mobile);
            }
        }catch (\Exception $e){
            //$this->error($e->getMessage());
            return "";
        }
        if($expressData && isset($expressData['data']) && !is_array($expressData['data'])){
            $expressData['data'] = json_decode($expressData['data'],true);
        }
        return $expressData;
    }

    /** 设置，存储物流信息
     * @param $order_id
     * @param $express_number
     * @param $express_name
     * @return bool|mixed
     * @throws \Exception
     */
    private  function setExpressData($express_number,$express_name='',$mobile=''){
        if(empty($express_number)){
            throw new \Exception('参数有误');
        }

        $data =  Express100::getExpressInfo($express_number,$mobile);

        if(empty($data) || empty($data['data'])){
            throw new \Exception('还未有物流信息');
        }
        $info = Db::name("order_express")->where(['express_number'=>$express_number])->find();
        $nowTime = time();
        if($info){
            Db::name("order_express")->where(['id'=>$info['id']])->update(['data'=>json_encode($data,JSON_UNESCAPED_UNICODE),'updatetime'=>$nowTime]);
        }else{
            $model = new OrderExpress();
            $data =[
                'order_no'=>'',
                'express_number'=>$express_number,
                'express_name'=>$express_name,
                'data'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'createtime'=>$nowTime,
                'updatetime'=>$nowTime
            ];
            $model->allowField(true)->save($data);
        }
        return $data;
    }


    //包裹完成
    public function sign()
    {
        $packageId = $this->request->param('package_id', 0, 'trim');
        $sign_images = $this->request->param('images');
        $remark = $this->request->param('remark');
        $package = new \app\admin\model\express\Package();
        $packageInfo = $package->where(['express_no' => $packageId])->find();
        if (empty($packageInfo)) {
            $this->error("包裹不存在");
        }
        if ($packageInfo->status != 2) {
            $this->error("该订单暂时不能完成");
        }

        $packageInfo->status = 3;
        $packageInfo->signtime = time();
        $packageInfo->sign_images = $sign_images;
        $packageInfo->sign_remark = $remark;

        $model = new Packagetrack();
        $log = [
            'package_id'=>$packageInfo['id'],
            'track_id'=>0,
            'msg'=>"包裹已签收",
            'admin_id'=>0,
            'createtime'=>time()
        ];
        $model->allowField(true)->save($log);

        $res = $packageInfo->save();
        if ($res) {
            $this->success("签收成功");
        }



        $this->error("提交失败");
    }


}
